package ltd.bugs.cute.common.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Spring的context，封装成静态方法方便获取bean
 * 
 * @author zhengzhq
 *
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
  private static ApplicationContext CONTEXT = null;

  @Override
  public void setApplicationContext(ApplicationContext context) throws BeansException {
    CONTEXT = context;
  }

  public static <T> T getBean(Class<T> classz) {
    return CONTEXT.getBean(classz);
  }

  @SuppressWarnings("unchecked")
  public static <T> T getBean(String name, Class<T> type) {
    return (T) CONTEXT.getBean(name);
  }

  public static void registerBean(String beanDefinitionXmlPath) {
    if (!(CONTEXT instanceof ConfigurableApplicationContext)) {
      throw new RuntimeException("bean '{}' register error, unsupport spring context!");
    }

    ConfigurableApplicationContext configurableApplicationContext =
        (ConfigurableApplicationContext) CONTEXT;
    BeanDefinitionRegistry beanDefinitionRegistry =
        (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();

    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(beanDefinitionRegistry);
    xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    xmlReader.loadBeanDefinitions(beanDefinitionXmlPath);
  }
}
